import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../pages/Home.vue'
import Login from '../pages/Login.vue'
import List from '../pages/List.vue'
import Publish from '../pages/Publish.vue'

Vue.use(VueRouter)

// 使用下面四行代码  把 错误进行拦截 并不处理
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/home/list' },
    { path: '/login', name: 'login', component: Login },
    {
      path: '/home',
      name: 'home',
      component: Home,
      children: [
        { path: 'list', name: 'list', component: List },
        { path: 'publish', name: 'publish', component: Publish },
      ],
    },
  ],
})

// 全局的导航守卫
router.beforeEach((to, from, next) => {
  let authUrlArr = ['/home/list', '/home/publish']
  let token = localStorage.getItem('token')

  if (authUrlArr.includes(to.path)) {
    // 进一步判断
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
